package com.lagou.service.user.service.impl;

import com.lagou.service.user.dao.TokenInfoDAO;
import com.lagou.service.user.dao.UserDAO;
import com.lagou.service.user.pojo.TokenInfo;
import com.lagou.service.user.pojo.User;
import com.lagou.service.user.service.UserService;
import com.lagou.service.user.service.feign.CodeServiceFeignClient;
import com.lagou.common.util.CommonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private TokenInfoDAO tokenInfoDAO;

    @Autowired
    private CodeServiceFeignClient codeServiceFeignClient;

    @Override
    public Integer register(String email, String password, String code) {

        /** 1 检查是否注册过 */
        if (isRegistered(email)) {
            // 已经注册过的场合
            return 3;
        }

        /** 2 检查验证码 */
        Integer result = codeServiceFeignClient.validate(email, code);
        if (result != 0) {
            if (result == 1) {
                // 验证码错误的场合
                return 1;

            } else if (result == 2) {
                // 验证码超时的场合
                return 2;
            }
        }

        /** 3 注册处理 */
        User user = new User();
        user.setEmail(email);
        user.setPassword(CommonUtils.toMd5(password));
        user.setCreateTime(CommonUtils.now());

        try {
            userDAO.save(user);
        } catch (Exception e) {
            e.printStackTrace();

            // 注册失败的场合
            return 4;
        }

        /** 4 生成token，存入数据库，并放入cookie */
        token(email, password);

        // 注册成功的场合
        return 0;
    }

    @Override
    public Boolean isRegistered(String email) {
        return userDAO.existsByEmail(email);
    }

    @Override
    public String login(String email, String password) {

        /** 1 登录验证 */
        // 根据邮箱查询用户信息
        User user = userDAO.findByEmail(email);

        // 用户信息不存在或者密码不正确的场合，返回null
        if (user == null || !user.getPassword().equals(CommonUtils.toMd5(password))) {
            return null;
        }

        /** 2 生成token，存入数据库，并放入cookie */
        token(email, password);

        /** 3 返回用户邮箱 */
        // 用户邮箱和密码都正确的场合，登录成功，返回邮箱
        return email;
    }

    @Override
    public String info(String token) {
        TokenInfo tokenInfo = tokenInfoDAO.findByToken(token);
        if (tokenInfo == null) {
            return null;
        }
        return tokenInfo.getEmail();
    }

    private void token(String email, String password) {
        String tokenValue = CommonUtils.generateToken(email, password);

        TokenInfo tokenInfo = new TokenInfo();
        tokenInfo.setEmail(email);
        tokenInfo.setToken(tokenValue);
        tokenInfo.setCreateTime(CommonUtils.now());
        tokenInfoDAO.save(tokenInfo);

        Cookie cookie = new Cookie("token", tokenValue);
        cookie.setPath("/");
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.addCookie(cookie);
    }
}
